package com.gzrhhscd.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class AliOSSUtils {
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint  ;
//    @Value("${aliyun.oss.accessKeyId}")
//    private String accessKeyId;
//    @Value("${aliyun.oss.secretAccessKey}")
//    private String secretAccessKey;
//    @Value("${aliyun.oss.bucketName}")
//   private String bucketName ;
    @Autowired
    private AliOSSProperties aliOSSProperties;
    public String upload(MultipartFile file) throws IOException {
        String endpoint=aliOSSProperties.getEndpoint();
        String accessKeyId=aliOSSProperties.getAccessKeyId();
        String secretAccessKey=aliOSSProperties.getSecretAccessKey();
        String bucketName=aliOSSProperties.getBucketName();
        //1.get file input stream;
        InputStream inputStream = file.getInputStream();
        //2.avoid same file name
        String originalFilename = file.getOriginalFilename();
        int index=originalFilename.indexOf(".");
        String extName=originalFilename.substring(index);
        String fileName= UUID.randomUUID()+extName;
        //3.upload file to OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,secretAccessKey);
        ossClient.putObject(bucketName,fileName,inputStream);
        //4.url
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        ossClient.shutdown();
        return url;
    }
}
